import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  useCallback,
} from "react";
import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { Input, Checkbox, Rate, Collapse, Modal, Upload, message, Popover } from 'antd';
import robotIcon from "../../../assets/images/robot1.png";
import refreshIcon from "../../../assets/images/refresh.png";
import readAloudIcon from "../../../assets/images/readAloud.png";
import cannotReadIcon from "../../../assets/images/canotRead.png";
import fileCloseIcon from "../../../assets/images/fileClose.png";
import xleThumbnailIcon from "../../../assets/images/xleThumbnail.png";
import enterIcon from "../../../assets/images/enter.png";
import canNotEnterIcon from "../../../assets/images/canNotEnter.png";
import stopIcon from "../../../assets/images/stop.png";
import leftIcon from "../../../assets/images/left-icon.png";
import recommendCloseIcon from "../../../assets/images/recommendClose.png";
import vectorIcon from "../../../assets/images/vector.png";
import skActiveIcon from "../../../assets/images/sk-a.png";
import skIcon from "../../../assets/images/sk.png";
import AssistantLeft from "./assistant-left";
import SquareEnd from "./file";
import language from "../../../lang/zh";
import { marked } from "marked";
import axios from "axios";
import homeLogo from '../../../assets/new_home/home-logo.png'
import notice from '../../../assets/new_home/notice.png'
import addChart from "../../../assets/new_home/add-chart.png"
import openIcon from "../../../assets/new_home/open-icon.png"
import send from "../../../assets/new_home/send.png"
import symbols from "../../../assets/new_home/@.png"
import paper from "../../../assets/new_home/paper.png"
import line from "../../../assets/new_home/line.png"
import sendLight from "../../../assets/new_home/linght-send.png"

import lineContainer from "../../../assets/new_home/line-container.png"
import { sendChatMessage,getMessagesList } from '../../../config/api/home';
 import {  fetchSharePointListData } from '../../../config/api/api.js';
const { TextArea } = Input;
const { Panel } = Collapse;
const { Group: CheckboxGroup } = Checkbox;
const AssistantContainer = ({
  bot_id = "app-7sIPOisuxuQCwMapf3GBojjQ",
  conversation_id: initialConversationId = "",
  utils,
  showToast,
  pageName = "问答",
  bot_index,
  graphClient,
  calendarEvents,
  originPageType=true 
}) => {
  
  
  
  // 添加状态变量
  const [currentBotId, setCurrentBotId] = useState(bot_id);
  const [currentConversationId, setCurrentConversationId] = useState(initialConversationId);
  // Removed isFather state
  
  useEffect(() => {
    console.log('AssistantContainer received new bot_id:', bot_id);
    console.log('AssistantContainer received new initialConversationId:', initialConversationId);
    setCurrentBotId(bot_id);
    setCurrentConversationId(initialConversationId);
  }, [bot_id, initialConversationId]);
  const  [cardList ,setCardList] = useState([])
  const  getRecommendList = async ()=>{
    const items = await fetchSharePointListData('0d1ea88b-c8e5-4b8f-b75a-35616f18aeb9');
    console.log("items",items)
  const tablelist =  items.map(item=>{
      return {
        id:item.id,
              title: item.Title,
      content: item.content,
      iconUrl:  item.attachmentUrls.length>0?item.attachmentUrls[0]:'',
      dept:item.labels
      }
    })
    setCardList(tablelist)
  }
  useEffect(() => {
    getRecommendList();
  }, []); 
  const [state, setState] = useState({
    isShowLikePopover: false,
    isYouKnown: false,
    questionType: 1,
    cancleLikeID: null,
    cancleLikeStatus: null,
    feedBackChecked: [],
    feedBackText: "",
    isShowVoiceInput: false,
    showFeedBack: false,
    feedBackSelect: [],
    inputFieldFocus: false,
    guessList: [],
    floatBottom: 0,
    activeNames: [""],
    activeNames1: ["1"],
    currentIndex: 0,
    sendText: "",
    classiFicationData: "",
    showArea: false,
    isPopverClose: true,
    isShowReco: false,
    isNewWindow: false,
    list: [],
    userInfo: null,
    eventSource: null,
    quizClassification: null,
    showConsultation: false,
    contentPadding: 0,
    consultationList: [],
    printEnd: false,
    printBackHtml: "",
    printAllHtml: "",
    isDisabled: false,
    isWait: false,
    messages: [],
    sendHidenText: "",
    userScrolled: false,
    answerObj: null,
    homeInfo: null,
    actionStop: false,
    feedBackScore: 0,
    checkedLang: false,
    weekdays: [],
    isReading: false,
    imgList: [],
    fileList: [],
    controller: null,
    modelType: false,
    isSk: false,
    printThinkAllHtml: "",
    printThinkBackHtml: "",
    fileLoading: false,
    currentTaskId: null, // Add this new state
    selectedAgent: null,
    sessionId: initialConversationId,
  });
  const currentIndexRef = useRef(0);
  const [questionType, setQuestionType] = useState(1);
  const [showFeedBack, setShowFeedBack] = useState(false);
  const [isDisabled, setIsDisabled] = useState(false);
  const [checkedLang, setCheckedLang] = useState(false);
  const [imgList, setImgList] = useState([]);
  const [fileList, setFileList] = useState([]);
  const [showPage, setshowPage] = useState("问答");
  const [isVisibleAssistantLeft, setIsVisibleAssistantLeft] = useState(true);
  const [isVisibleRecommend, setIsVisibleRecommend] = useState(true);
  const [isVisibleRecommendIcon, setIsVisibleRecommendIcon] = useState(false);
  const [isVisibleRecommendPopup, setIsVisibleRecommendPopup] = useState(false);
  const [followUpContents, setFollowUpContents] = useState([]);
  const [isSearch, setIsSearch] = useState(false);
  const timeoutId = useRef(null);
  const isRoll = useRef(false)
  const [weekdays, setWeekdays] = useState(checkedLang
    ? ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    : ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]);
  const input = useRef(null);
  const scrollContainer = useRef(null);
  const assistantLeftRef = useRef(null);
  const [sessionLoading, setSessionLoading] = useState(false);
  const [newHistoryItem, setNewHistoryItem] = useState(null);
  const historyPanelRef = useRef(null);
  const [disableInitialSelection, setDisableInitialSelection] = useState(false);
  const [selectedHistoryItem, setSelectedHistoryItem] = useState(null);
  const scrollIntervalRef = useRef(null);

  useEffect(() => {
    setWeekdays(checkedLang
      ? ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
      : ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]);
  }, [checkedLang]);

  useEffect(() => {
    setshowPage(pageName);
    if (initialConversationId || bot_id !== "app-7sIPOisuxuQCwMapf3GBojjQ") {
        console.log('Disabling initial selection in AssistantLeft due to initialConversationId or bot_id prop change.');
        setDisableInitialSelection(true);
    } else {
        setDisableInitialSelection(false);
    }

  }, [currentBotId, pageName, initialConversationId, createSession, bot_id]); 

  useEffect(() => {
    const initializeState = async () => {

      if (initialConversationId) {
        setCurrentConversationId(initialConversationId);
        setState(prev => ({
          ...prev,
          sessionId: initialConversationId,
          consultationList: []
        }));
        await pollForAnswer(true, false, initialConversationId, bot_id); // Pass bot_id for the initial fetch
         setIsVisibleRecommend(false); // Hide recommend when loading specific history

      } else if (originPageType === false) { // If navigating from AI Square chat card or similar (originPageType is false)
         setCurrentBotId(bot_id);
         setCurrentConversationId('');
         setState(prev => ({
           ...prev,
           sessionId: '',
           selectedAgent: null,
           consultationList: []
         }));
         setIsVisibleRecommend(true); // Show recommend
         setSelectedHistoryItem(null); // Clear history selection

      } else {
         setCurrentBotId(bot_id);
         setCurrentConversationId('');
         setState(prev => ({
           ...prev,
           sessionId: '',
           selectedAgent: null,
           consultationList: []
         }));
         setIsVisibleRecommend(true); // Show recommend
         setSelectedHistoryItem(null); // Clear history selection
      }
    };

    initializeState();
  }, [bot_id, initialConversationId, originPageType, pollForAnswer]); // Add pollForAnswer to dependencies

  useEffect(() => {
    if (initialConversationId) {
      console.log('AssistantContainer mounted with initialConversationId prop:', initialConversationId);
      setCurrentConversationId(initialConversationId);
      pollForAnswer(false, false, initialConversationId);
    } else {
      setCurrentConversationId('');
      setState(prev => ({
        ...prev,
        sessionId: '',
        selectedAgent: null,
        consultationList: []
      }));
       setIsVisibleRecommend(true);
       setSelectedHistoryItem(null);
    }
  }, [initialConversationId, pollForAnswer]);

  useEffect(() => {
    if (bot_id && !initialConversationId) {
      setCurrentBotId(bot_id);
      setCurrentConversationId('');
      setState(prev => ({
        ...prev,
        sessionId: '',
        selectedAgent: null,
        consultationList: [] // 清空消息列表
      }));
      setIsVisibleRecommend(true);
    }
  }, [bot_id, initialConversationId]);

  const handleKeyDown = (event) => {
    if (event.shiftKey && event.key === 'Enter') {
      event.preventDefault();
      setSendText(prevText => prevText + '\n');
    } else if (event.key === 'Enter') {
      event.preventDefault();
      sendQa();
    }
  };
  const getFileDetails = (item) => {
    return new Promise((resolve) => {
      if (item.resourceFile && item.fileId) {
        let urls = item.resourceFile.split(",");
        let ids = item.fileId.split(",");
        let docList = [];
        for (let i = 0; i < urls.length; i++) {
          const url = urls[i];
          axios(url, { method: "HEAD" })
            .then((response) => {
              const fileName = url.substring(url.lastIndexOf("/") + 1);
              docList.push({
                fileName: fileName.includes('_') ? fileName.substring(0, fileName.lastIndexOf('_')) : fileName,
                fileUrl: url,
                fileId: ids[i],
                fileType: fileName.split('.').pop().toLowerCase(),
              });
              if (docList.length === urls.length) {
                resolve(docList);
              }
            })
            .catch((error) => {
              console.error("Unable to get file information", error);
            });
        }
      }
    });
  };
  const containerStyle = {
    height: (imgList.length > 0 || (fileList.length > 0 && !isDisabled)) ? "53.9294vh" : "64.009vh",
  };
  const onRateChange = (value, item) => {
    setFeedBackScore(value);

    setConsultationList(prevData => {
      return prevData.map(i => {
        if (i.requestId === item.requestId) {
          return { ...i, isShowRateOpBox: true };
        }
        return i;
      });
    });
  };
  const handleClick = (event) => {
    const target = event.target;
    if (target.matches(".phone-tips")) {
      setConsultationList(prevList => {
        return prevList.map(item => {
          if (item.requestId && item.requestId === target.getAttribute("data-id")) {
            return { ...item, activeNames1: ["1"] };
          }
          return item;
        });
      });
    }
    if (target.matches(".doc-tips")) {
      const position = target.getAttribute("data-position");
      if (position) {
        scrollToPosition(position);
      }
    }
  };
  const readText = (text) => {
  
    text = text.replace(/<.*?>/g, "");
    if (text) {
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = checkedLang ? "en-US" : "zh-CN";
      utterance.pitch = 1;
      utterance.rate = 1;
      utterance.addEventListener("end", onReadEnd);
      speechSynthesis.speak(utterance);
      setIsReading(true);
    }
  };
  const onReadEnd = () => {
    setIsReading(false);
  };
  const stopReading = () => {
    if (speechSynthesis.speaking) {
      speechSynthesis.cancel();
      setIsReading(false);
    }
  };
  const toggleVisibility = useCallback((type) => {
    if (type === 1) { // 使用严格相等判断
      setIsVisibleRecommendIcon(prev => !prev);
      setIsVisibleRecommendPopup(prev => !prev);
    } else if (isVisibleRecommend) {
      setIsVisibleRecommend(false);
      setIsVisibleRecommendIcon(true);
    }
  }, [isVisibleRecommend]); // 添加依赖项
  const scrollToPosition = (position) => {
    let attr = position.split("%");
    let indexs = attr[1].replace(/\[|\]/g, "");
    const element = document.getElementsByClassName(`${attr[0]}`);

    setConsultationList(prevList => {
      const newList = [...prevList];

      for (let i = 0; i < newList.length; i++) {
        if (
          newList[i].questionType &&
          newList[i].questionType === 1 &&
          newList[i].requestId === attr[0]
        ) {
          newList[i].activeNames = ["1"];

          if (
            newList[i].answerRaw &&
            newList[i].answerRaw.docReferencesDistinct?.length > 0
          ) {
            newList[i].answerRaw.docReferencesDistinct.forEach((j) => {
              j.active = hasCommonCharacters(indexs, j.indexId.toString());
            });
          }
        } else if (newList[i].questionType && newList[i].questionType === 1) {
          newList[i].activeNames = [];

          if (
            newList[i].answerRaw &&
            newList[i].answerRaw.docReferencesDistinct?.length > 0
          ) {
            newList[i].answerRaw.docReferencesDistinct.forEach((j) => {
              j.active = false;
            });
          }
        }
      }

      return newList;
    });

    if (scrollContainer && scrollContainer.current) {
      scrollContainer.current.scrollTop =
        element[0].offsetTop + scrollContainer.current.scrollTop + 100
    }
  };
  const sendQa = () => {
    if (imgList.length > 0 || questionType === 6) {
      if (questionType !== 6) {
        setIsNewWindow(true);
        input.current.focus();
        setConsultationList([]);
        setGuessList([]);
 
        setIsShowLikePopover(false);
        window.scrollTo(0, document.body.scrollHeight);
      }
      setQuestionType(6);
    }

    if (questionType !== 7 && questionType !== 8 && fileList.length > 0) {
      setIsNewWindow(true);
      input.current.focus();
      setConsultationList([]);
      setGuessList([]);

      setIsShowLikePopover(false);
      window.scrollTo(0, document.body.scrollHeight);
      setQuestionType(7);
    } else if (questionType === 7 && fileList.length >= 0) {
      setFileList([]);
      setQuestionType(7);
    }
    initSSE();
    toggleVisibility(0);
  };
  const hasCommonCharacters = (str1, str2) => {
    const set2 = new Set(str2.split(","));
    for (let char of set2) {
      if (str1.includes(char)) {
        return true;
      }
    }
    return false;
  };
  const addInpitValue = (sendText)=>{
    setState(prev => ({
      ...prev,
      sendText:sendText

    }));
  }
  console.log("11111111111")
  const openFile = (e) => {
    if (e.filePath) {
      location.href = e.filePath;
    } else {
      alert("No source document path available");
    }
  };
  const openNewWindow = (type = 1) => {
    if (type === 2) {
      if (pageName === "问答") {
        setshowPage("问答");
        createSession(true);
      }
    } else if (type === 3) {
      createSession(true);
    }
    setIsVisibleRecommend(true);
    setIsVisibleRecommendIcon(false);
    setIsVisibleRecommendPopup(false);
    setIsNewWindow(true);
    input.current?.focus();
    setConsultationList([]);
    setGuessList([]);

    setQuestionType(type);
    setIsShowLikePopover(false);
    window.scrollTo(0, document.body.scrollHeight);
    stopReceiveData(2);
    alert(checkedLang ? language.messageEN.newTalk : language.messageZH.newTalk);
  };
  const changeLange = () => {
    setCheckedLang(prev => !prev);
    if (parentCheckedLang) {
      parentCheckedLang(!checkedLang);
    }
    getFeedBackSelect();
  };
  const bindRefresh = async (item) => {
    setSendHidenText(item.questionContent);

    if (questionType === 6 && item.resourceFile) {
      const uploadedFile = {
        imgUrl: item.resourceFile,
      };
      setImgList([uploadedFile]);
    }

    if (questionType === 7 && item.resourceFile) {
      const files = await getFileDetails(item);
      setFileList(files);
    }

    initSSE();
  };
  const stopReceiveData = useCallback(async (type) => {
    if (state.currentTaskId) {
      try {
        await fetch(`/api/chat-messages/${state.currentTaskId}/stop`, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + currentBotId,
            'Content-Type': 'application/json'
          },
          data:{ "user": "user11",}
        });
      } catch (error) {
        console.error('Error stopping message:', error);
      }
    }
    setState(prev => ({
      ...prev,
      isDisabled: false,
      printEnd: true,
      currentTaskId: null,
      actionStop: true
    }));
  }, [state.currentTaskId, currentBotId]);

  const getFooterHeight = useCallback(() => {
    setState(prev => ({ ...prev, inputFieldFocus: false }));
    setTimeout(() => {
      const footerHeight = document.querySelector(".assistant-footer")?.clientHeight;
      setState(prev => ({ ...prev, floatBottom: footerHeight }));
      return footerHeight || 54;
    }, 0);
  }, []);

  // 清除滚动定时器
  const clearScrollInterval = useCallback(() => {
    if (scrollIntervalRef.current) {
      clearInterval(scrollIntervalRef.current);
      scrollIntervalRef.current = null;
    }
  }, []);

  // 添加wheel事件监听
  useEffect(() => {
    const container = scrollContainer.current;
    if (container) {
      const handleWheel = () => {
        isRoll.current = false;
        setState(prev => ({ ...prev, userScrolled: true }));
        clearScrollInterval(); // 清除滚动定时器
      };

      container.addEventListener('wheel', handleWheel);
      return () => container.removeEventListener('wheel', handleWheel);
    }
  }, [clearScrollInterval]);

  // 添加scroll事件监听
  useEffect(() => {
    const container = scrollContainer.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, []);

  const handleScroll = useCallback(() => {
    if (scrollContainer && scrollContainer.current) {
      const { scrollTop, clientHeight, scrollHeight } = scrollContainer.current;
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 10;
      
      if (!isNearBottom) {
        setState(prev => ({ ...prev, userScrolled: true }));
      } else {
        setState(prev => ({ ...prev, userScrolled: false }));
        isRoll.current = true; // 只有在底部时才恢复自动滚动
      }
    }
  }, []);

  const scrollToBottom = useCallback(() => {
    if (!isRoll.current) {
      return;
    }

    if (scrollContainer && scrollContainer.current) {
      setTimeout(() => {
        const contentHeight = scrollContainer.current.scrollHeight;
        const visibleHeight = scrollContainer.current.clientHeight;
        const footerHeight = document.querySelector(".assistant-footer")?.clientHeight || 80;
        const scrollPosition = contentHeight - visibleHeight + footerHeight;
        scrollContainer.current.scrollTop = scrollPosition;
      }, 150);
    }
  }, []);

  // 监听消息列表变化
  useEffect(() => {
    if (state.consultationList.length > 0 && !state.userScrolled) {
      scrollToBottom();
    }
  }, [state.printEnd, state.consultationList.length, state.userScrolled]);

  // 监听打字效果状态
  useEffect(() => {
    if (!state.printEnd && !state.userScrolled) {
      // 清除之前的定时器
      clearScrollInterval();
      // 设置新的定时器
      scrollIntervalRef.current = setInterval(scrollToBottom, 300);
    }
    return () => clearScrollInterval();
  }, [state.printEnd, state.userScrolled, scrollToBottom, clearScrollInterval]);

  // 重置滚动状态
  const resetScrollState = useCallback(() => {
    isRoll.current = true;
    setState(prev => ({ ...prev, userScrolled: false }));
    clearScrollInterval(); // 清除滚动定时器
  }, [clearScrollInterval]);

  // 在开始新对话时重置滚动状态
  useEffect(() => {
    if (!currentConversationId) {
      resetScrollState();
    }
  }, [currentConversationId, resetScrollState]);

  // 在发送消息时重置滚动状态
  const initSSE = useCallback((message) => {
    const sendText = state.sendText || state.sendHidenText || message;
    if (!sendText) {
      showToast("发送内容不能为空");
      return false;
    }
    if (state.isWait || state.isDisabled) {
      return;
    }

    // 重置滚动状态
    resetScrollState();
    isRoll.current = true;

    const isFatherValue = !currentConversationId;
    console.log("!currentConversationId", !currentConversationId);
    
    if (!currentConversationId) {
      const tempHistoryItem = {
        id: '-1', // Temporary ID
        title: sendText, // User's message as the title
        answer: '', // No answer yet
        createTime: new Date().toISOString(),
        sessionId: '', // No session ID yet initially
        token: currentBotId, // Include bot_id
        isFather: isFatherValue, // Use calculated isFatherValue here for temp item
      };
      setNewHistoryItem(tempHistoryItem); // Pass to AssistantLeft

      setState(prev => ({
        ...prev,
        isDisabled: true,
        isNewWindow: false,
        isShowReco: false,
        isWait: true,
        printBackHtml: "",
        guessList: [],
        showConsultation: true,
        consultationList: [
          { text: sendText, type: 0, imgList: prev.imgList, fileList: prev.fileList, printEnd: true }, // User message
          { text: '', type: 1, imgList: [], fileList: [], printEnd: false } // Assistant placeholder
        ],
        sendText: ""
      }));

      setIsVisibleRecommend(false);
      if (scrollContainer && scrollContainer.current) {
        scrollToBottom();
      }

      initTextSSE(sendText, isFatherValue); // Pass isFatherValue
    } else {
      setState(prev => ({
        ...prev,
        isDisabled: true,
        isNewWindow: false,
        isShowReco: false,
        isWait: true,
        consultationList: [
          ...prev.consultationList,
          { text: sendText, type: 0, imgList: prev.imgList, fileList: prev.fileList, printEnd: true }, // User message
          { text: '', type: 1, imgList: [], fileList: [], printEnd: false } // Assistant placeholder
        ],
        sendText: ""
      }));

      setIsVisibleRecommend(false);
      if (scrollContainer && scrollContainer.current) {
        scrollToBottom();
      }

      initTextSSE(sendText, isFatherValue); // Pass isFatherValue
    }
  }, [state, showToast, resetScrollState, currentConversationId, currentBotId, setNewHistoryItem, initTextSSE, scrollToBottom]);

  const getMessages = useCallback(async (sessionId, botId) => {
    const botIdToUse = botId || currentBotId;
    try {
      const params = {
        "user": "user11",
        "conversation_id": sessionId || currentConversationId || '',
        "order": "ASC"
      }
      const response = await getMessagesList(params, botIdToUse);

      if (response && response.data) {
        return { data: response.data.data };
      } else {
        return { data: [] };
      }
    } catch (error) {
      console.error('Error in getMessages:', error);
      return { data: [] };
    }
  }, [currentBotId, currentConversationId]); // Keep dependencies as they are still fallbacks

  const updateContent = useCallback((data) => {
      // setState(prev => ({
      //   ...prev,

      //   isDisabled: true,
      // }));
    isRoll.current = true
    if (currentIndexRef.current < data.length) {
      let currentChar = data[currentIndexRef.current];
      if (currentChar !== undefined) {
        setState(prev => ({
          ...prev,
          printBackHtml: prev.printBackHtml + currentChar,
        }));

      }

      currentIndexRef.current += 1;
      timeoutId.current = setTimeout(() => {
        updateContent(data);
      }, 100); // 减少延迟时间，使打字效果更流畅
    } else {
      setIsDisabled(false);
      isRoll.current = false
      setState(prev => ({
        ...prev,
        sendHidenText: '',
        printEnd: false,
        isWait: false,
   
      }));

    }

  }, [state.currentIndex, state.printAllHtml, state.printBackHtml]);

  // 新增历史记录方法
  const addDialogueHistory = async ({ askContent, answerContent, userId, sessionId: receivedSessionId, isFatherValue }) => {
    console.log('addDialogueHistory received sessionId:', receivedSessionId);
    try {
      const response = await fetch('https://55au18tn8357.vicp.fun/prod-api/system/message', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
         question: askContent, 
        content:  answerContent, 
          userId, 
          sessionId: receivedSessionId || '', // Ensure null is passed if empty
          token: currentBotId,
          isFather: !currentConversationId // true when currentConversationId is empty, false when it has a value
        })
      });
      const data = await response.json();
      if (data.code === 200) {
        if (!currentConversationId) {
          historyPanelRef.current.fetchHistory();
        }
        return data;
      } else {
        console.error('新增历史记录失败:', data.msg);
        return null;
      }
    } catch (err) {
      console.error('请求出错:', err);
      return null;
    }
  };

  const pollForAnswer = useCallback(async (isUpdateContent = true, isAddHistory = true, sessionId, botId, isFatherValue) => {
    isRoll.current = true;
    let response = await getMessages(sessionId, botId);

    if (!response.data || response.data.length === 0) {
      if (sessionId) {
        setState(prevState => ({
          ...prevState,
          consultationList: [],
          printBackHtml: '',
          printAllHtml: '',
          isWait: false,
          printEnd: false,
          isDisabled: false, // Changed from true to false
        }));
        setCurrentConversationId(''); 
        setIsVisibleRecommend(true); 
      }
      return;
    }
    const consultationList = response.data.flatMap((item) => {
      const questionResult = {
        text: item.query,
        type: 0,
        imgList: [],
        fileList: [],
        answerContent: item.answer,
        printEnd: false,
      };
      const answerResult = {
        text: item.answer, // Changed from item.query to item.answer
        type: 1,
        imgList: [],
        fileList: [],
        answerContent: item.answer,
        printEnd: true,
      };
      return [questionResult, answerResult];
    });

    setState(prevState => ({
      ...prevState,
      sendText: '',
      isWait: false,
      printEnd: false,
      isDisabled: false, // Changed from true to false
      printAllHtml: consultationList[consultationList.length - 1].answerContent,
      currentIndex: 0,
      consultationList: consultationList,
      selectedAgent: prevState.selectedAgent // 保持选中的智能体
    }));
    setIsVisibleRecommend(false);
    if (isUpdateContent && response.data.length > 0) {
    } else if (response.data.length > 0) {
      setState(prevState => ({
        ...prevState,
        printBackHtml: consultationList[consultationList.length - 1].answerContent,
        selectedAgent: prevState.selectedAgent // 保持选中的智能体
      }));
    }
  }, [getMessages, updateContent]);

  const createSession = useCallback(async ({ isNew = true, sessionId = null } = {}) => {
    if (isNew) {
      setCurrentConversationId(''); 
      setState(prevState => ({
        ...prevState,
        isWait: false,
        printEnd: false,
        isDisabled: false,
        consultationList: [],
        printBackHtml: '',
        printAllHtml: '',
        sessionId: '' // 清空sessionId
      }));
      setIsVisibleRecommend(true);
      // 通过状态控制历史记录选择
      setSelectedHistoryItem(null);
    } 
  }, [currentBotId]);

  const handleItemSelected = async (item) => {

    const foundAgent = agentList ? agentList.find(agent => agent.bot_id === item.token) : null;
    if (!item) return;

    setState(prev => ({
      ...prev,
      selectedAgent: foundAgent, 
      sessionId: item.sessionId,
      consultationList: [],     
      printBackHtml: '',        
      printAllHtml: '' ,

      isDisabled:false          
    }));

    setCurrentConversationId(item.sessionId);
    setSelectedHistoryItem(item);          
    setCurrentBotId(item.token);           
    setIsVisibleRecommend(false);         

    await pollForAnswer(true, false, item.sessionId, item.token); 
  };

  const handleAgentSelect = (agent) => {
    setState(prev => ({
      ...prev,
      selectedAgent: agent
    }));
    setCurrentConversationId('');
    setCurrentBotId(agent.bot_id); 
    setState(prev => ({
      ...prev,
      sessionId: '',
      consultationList: []
    }));
    setSelectedHistoryItem(null);
    setIsVisibleRecommend(true);
  };

  const sendMessage = useCallback(
    async (sendText, isFatherValue) => {
      try {
        const botId = selectedHistoryItem?.token || state.selectedAgent?.bot_id || currentBotId;
        currentIndexRef.current = 0;
        
        const conversationId = currentConversationId;
        
        setState(prev => ({
          ...prev,
          printBackHtml: '',
          printAllHtml: '',
          imgList: [],
          selectedAgent: prev.selectedAgent 
        }));

        const headers = {
          Authorization: "Bearer " + botId,
          "Content-Type": "application/json",
        };

        const requestData = {
          "inputs": {},
          "query": sendText,
          "response_mode": "streaming",
          "conversation_id": conversationId || '',
          "user": "user11",
          "files": [
            {
              "type": "image",
              "transfer_method": "remote_url",
              "url": ""
            }
          ]
        };
        const controller = new AbortController();
        const response = await fetch('https://zhi1develop.zicp.fun/v1/chat-messages', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestData),
          signal: controller.signal
        });
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let fullText = '';
        let taskId = null;
        setState(prev => ({
          ...prev,
          isWait: true,
          printEnd: true,
          imgList: [],
          isDisabled: true,
          selectedAgent: prev.selectedAgent 
        }));
 
        let finalConversationId = conversationId;
        while (true) {
          const { done, value } = await reader.read();
          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n').filter(line => line.trim() !== '');
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.substring(6));
                if (data.answer || data.message) {
                  const newContent = data.answer || data.message || '';
                  fullText += newContent;
                  updateContent(fullText);
                }
             
                if (data.conversation_id) {
                  finalConversationId = data.conversation_id;
                  if (!conversationId) { // Only update state for new conversations initially
                    setCurrentConversationId(data.conversation_id);
                    setState(prev => ({
                      ...prev,
                      sessionId: data.conversation_id,
                      selectedAgent: prev.selectedAgent 
                    }));
                    const newHistoryItemData = {
                      id: data.conversation_id, 
                      title: sendText,
                      answer: '', // 初始答案为空
                      createTime: new Date().toISOString(),
                      sessionId: data.conversation_id,
                      token: currentBotId,
                      isFather: currentConversationId?false:true, 
                    };
                    setNewHistoryItem(newHistoryItemData);
                    setSelectedHistoryItem(newHistoryItemData);
                  }
                }
          
              } catch (e) {
              }
            }
          }

          if(done){
      
                setState(prev => {
                    const updatedConsultationList = [...prev.consultationList];
                    if (updatedConsultationList.length > 0) {
                        updatedConsultationList[updatedConsultationList.length - 1] = {
                            ...updatedConsultationList[updatedConsultationList.length - 1],
                            text: fullText, // 设置最终的流式传输文本
                            answerContent: fullText, // 同时设置 answerContent
                            printEnd: true, // 标记为完成
                        };
                    }
                    return {
                        ...prev,
                        isDisabled: false,
                        consultationList: updatedConsultationList,
                    };
                });

       

                addDialogueHistory({
                   askContent: sendText, // 用户查询
                   answerContent: fullText, // 完整的回答
                   userId: 27,
                   sessionId: finalConversationId,
                   token: botId,
                   isFather: isFatherValue // Directly use the calculated isFatherValue
               });
             if(isFatherValue){
              const newHistoryItemData = {
                id: finalConversationId,
                title: sendText,
                answer: fullText, // 传递完整的回答
                createTime: new Date().toISOString(),
                sessionId: finalConversationId,
                token: botId,
                isFather: isFatherValue,
            };
            setNewHistoryItem(newHistoryItemData);
            setSelectedHistoryItem(newHistoryItemData);
             }
                break;
          }
        }

      } catch (error) {
        showToast("发送消息失败");
      }
    },
    [currentBotId, currentConversationId, state.selectedAgent, selectedHistoryItem, addDialogueHistory]
  );



  const [isPanelOpen, setIsPanelOpen] = useState(false);

  const togglePanel = () => {
    setIsPanelOpen(!isPanelOpen);
    setIsVisibleAssistantLeft(!isVisibleAssistantLeft);
  };
  

  const clickItemQa = useCallback((e, type) => {
    if (state.questionType === 6 || state.questionType === 7) {
    }

    setState(prev => ({
      ...prev,
      isPopverClose: false,
      isYouKnown: type !== 3,
      questionType: type,
    }));

    window.scrollTo(0, document.body.scrollHeight);

    if (!state.isDisabled) {
      setState(prev => ({ ...prev, sendHidenText: e }));
      initSSE();
    }
  }, [state.questionType, state.isDisabled]);

  const initTextSSE = useCallback(async (sendText, isFatherValue) => {
    setState(prev => ({ ...prev, printEnd: true }));
    isRoll.current = true;
    await sendMessage(sendText, isFatherValue); // Pass isFatherValue to sendMessage
    setState(prev => ({
      ...prev,
  
      isDisabled: false,
    }));
  }, [sendMessage]); // Dependency updated

  const initFileSSE = useCallback((sendText) => {
    const eventSourceUrl = process.env.VUE_APP_BASE_API_URL +
      `/wechatApi/calAliFileRag?questionContent=${encodeURIComponent(
        sendText
      )}&questionType=${state.questionType}&lang=${state.checkedLang ? "en" : "zh"
      }&token=${localStorage.getItem("token")}&requestTime=${moment().valueOf()}${state.sessionId ? `&sessionId=${state.sessionId}` : ''
      }`;

    const controller = new AbortController();
    const { signal } = controller;

    setState(prev => ({ ...prev, controller }));

    let imgList = [];
    let fileIdLis = [];

    if (state.fileList.length > 0) {
      imgList = state.fileList.map(item => item.fileUrl);
      fileIdLis = state.fileList.map(item => item.fileId);
    }
  
  }, [state.questionType, state.checkedLang, state.sessionId, state.fileList, updateContent]);

  const [selectedLang, setSelectedLang] = useState('zh'); // 默认选中中文
  const changeLanguage = (lang) => {
    setSelectedLang(lang);
  };

  const seachQuestion = useCallback((value) => {
    setState(prev => ({ ...prev, sendText: value }));
  }, []);

  const updateThinkContent = useCallback((data) => {
    if (state.currentIndex < state.printThinkAllHtml.length) {
      setState(prev => ({
        ...prev,
        printThinkBackHtml: prev.printThinkBackHtml + prev.printThinkAllHtml[prev.currentIndex],
        currentIndex: prev.currentIndex + 1
      }));

      setTimeout(() => {
        updateThinkContent(data);
      }, 50);
    }
  }, [state.currentIndex, state.printThinkAllHtml]);


  const backHtm = useMemo(() => {
    return marked(state.printBackHtml);
  }, [state.printBackHtml]);

  const backThinkHtm = useMemo(() => {
    return marked(state.printThinkBackHtml || "");
  }, [state.printThinkBackHtml]);

  const handleImageUpload = (info) => {
    if (info.file.status === 'uploading') {
      setState(prev => ({ ...prev, fileLoading: true }));
      return;
    }
    if (info.file.status === 'done') {
      setState(prev => ({ 
        ...prev, 
        fileLoading: false,
        imgList: [{
          imgUrl: info.file.response.url,
          imgName: info.file.name,
          imgType: info.file.type,
          imgSize: formatFileSize(info.file.size)
        }]
      }));
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      setState(prev => ({ ...prev, fileLoading: false }));
      message.error(`${info.file.name} 上传失败`);
    }
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const uploadProps = {
    name: 'file',
    action: '/api/files/upload',
    headers: {
      authorization: 'Bearer ' + currentBotId,
    },
    showUploadList: false,
    maxCount: 1,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    onChange: handleImageUpload,
  };

  const handleRemoveImage = () => {
    setState(prev => ({ ...prev, imgList: [] }));
  };

  const  [agentList ,setAgentList] = useState([])
    const getAgentList = async () => {
      const items = await fetchSharePointListData('c793107a-2558-4107-a18f-aed980c310cc');
      console.log("tablelist",items)
      let tablelist = items
      .filter(item => item.isChat==="true") 
      .map(item => {
        return {
          id: item.Id,
          title: item.Title,
          content: item.descrption,
          iconUrl: item.attachmentUrls.length > 0 ? item.attachmentUrls[0] : '',
          dept: item.labels,
          isChat: item.isChat==="true" ? '/home' : '',
          bot_id: item.bot_id,
        }
      });
      setAgentList(tablelist)

      if (bot_id) {
        const initialSelected = tablelist.find(agent => agent.bot_id === bot_id);
        if (initialSelected) {
          setState(prev => ({
            ...prev,
            selectedAgent: initialSelected,
          }));
        }
      }
    };

  useEffect(() => {
    getAgentList();
  }, [bot_id]); 

  const agentContent = (
    <div style={{ padding: '8px 0' }}>
      {agentList.map(agent => (
        <div
          key={agent.id}
          style={{
            padding: '8px 16px',
            cursor: 'pointer',
            backgroundColor: state.selectedAgent?.id === agent.id ? 'rgba(92, 178, 255, 0.1)' : 'transparent',
            transition: 'background-color 0.3s ease',
            ':hover': {
              backgroundColor: 'rgba(92, 178, 255, 0.1)'
            }
          }}
          onClick={() => handleAgentSelect(agent)}
        >
          {agent.title}
        </div>
      ))}
    </div>
  );

  const handleHistoryFirstItem = useCallback(async (item) => {
    if (item && item.sessionId && originPageType !== false) {
      setCurrentConversationId(item.sessionId);
      setState(prev => ({
        ...prev,
        sessionId: item.sessionId,
        consultationList: []
      }));
      setSelectedHistoryItem(item);
      isRoll.current = true; // 重置滚动状态
      
      // 加载选中历史记录的消息
      const botIdToUse = item.token || currentBotId;
      await pollForAnswer(true, false, item.sessionId, botIdToUse);
      
      // 确保滚动到底部
      if (scrollContainer && scrollContainer.current) {
        setTimeout(() => {
          scrollContainer.current.scrollTop = scrollContainer.current.scrollHeight;
        }, 100);
      }
    } else {
      setCurrentConversationId('');
      setState(prev => ({
        ...prev,
        sessionId: '',
        selectedAgent: null,
        consultationList: []
      }));
      setIsVisibleRecommend(true);
      setSelectedHistoryItem(null);
    }
  }, [pollForAnswer, currentBotId, originPageType]); // Add pollForAnswer and currentBotId to dependencies

  return (
    <div className="assistant-container">
      {pageName === '问答' && (
        <div className="assistant-right">
          <div className="right-head">
            {/* <div
              className="changeLange"
              style={{ opacity: state.questionType !== 8 ? '1' : '0' }}
            >
              {!state.checkedLang ? (
                <div
                  className="ZN"
                  onClick={() => state.questionType !== 8 ? changeLange() : ''}
                >
                  <div>
                    <span>中文</span>
                  </div>
                  <div>
                    <span>English</span>
                  </div>
                </div>
              ) : (
                <div className="EN" onClick={changeLange}>
                  <div>
                    <span>中文</span>
                  </div>
                  <div>
                    <span>English</span>
                  </div>
                </div>
              )}
            </div> */}

<div className={`new-chart ${state.isDisabled ? 'notAllow' : ''}`} onClick={state.isDisabled ? null : () => createSession(true)}>
  <img src={addChart} alt="新建聊天" />
  新建聊天
</div>
          {/* <div className="changeLange">
      <div
        className={`language-option ${selectedLang === 'zh' ? 'active-lang' : ''}`}
        onClick={() => changeLanguage('zh')}
      >
        中文
      </div>
      <span className="separator active-lang">|</span>
      <div
        className={`language-option ${selectedLang === 'en' ? 'active-lang' : ''}`}
        onClick={() => changeLanguage('en')}
      >
        English
      </div>
    </div> */}
    <img  src={openIcon}  onClick={togglePanel}  className={`cursor-pointer ${isPanelOpen ? 'active' : ''}`}></img>
            {((isVisibleAssistantLeft || isVisibleRecommendPopup) &&
              !(!isVisibleAssistantLeft && isVisibleRecommendPopup) &&
              !(isVisibleAssistantLeft && isVisibleRecommendPopup)) && (
                <div className="layout-1"></div>
              )}
            {(!isVisibleAssistantLeft && isVisibleRecommendPopup) && (
              <div className="layout-2"></div>
            )}
          </div>




          <div className={`content ${state.showConsultation ? 'consultation-mode' : ''}`}>
            <div
              className="consultation-container"
              style={containerStyle}
              onScroll={handleScroll}
            >
               {isVisibleRecommend && (
                <div className="greet">
                  {state.questionType !== 8 && state.consultationList.length === 0 && (

                    <div className="ai-icon">
                      <div><img src={homeLogo} />
                      </div>

                    </div>

                  )}
                  <div className="home-card">
                      {cardList.map((card) => (
                        <div
                          key={card.id}
                          className="card-item"
                          onClick={() => addInpitValue(card.content)}
                        >
                          
                          <div className="card-title-container">
                          <div className="notice-icon" ><img src={card.iconUrl}></img></div>
                            <div className="card-title">{card.title}</div>
                          </div>
                          <p className="card-desc">{card.content}</p>
                        </div>
                      ))}
                    </div>


                </div>
              )}



{!isVisibleRecommend && (
                <div className="session-box" ref={scrollContainer}>
                  {state.consultationList.map((item, index) => (
                    <React.Fragment key={index}>
                      {item.type === 0 && (
                        <div className="item itema">
                          <div className="con">
                            <div
                              className="con-text fs-16"
                              dangerouslySetInnerHTML={{ __html: item.text }}
                            ></div>
                          </div>
                          {item.imgList && item.imgList.length > 0 && item.imgList[0].imgUrl && (
                            <div className="img-qa">
                              {item.imgList.map((i, idx) => (
                                <img key={idx} src={i.imgUrl} alt="" />
                              ))}
                            </div>
                          )}
                          {item.imgList && item.imgList.length > 0 && !item.imgList[0].imgUrl && (
                            <div className="img-qa">
                              {item.imgList.map((i, idx) => (
                                <img key={idx} src={i} alt="" />
                              ))}
                            </div>
                          )}
                          {item.fileList && item.fileList.length > 0 && (
                            <div className="file-qa">
                              <div className="uploadImg">
                                {item.fileList.map((i, idx) => (
                                  <div className="img" key={idx}>
                                    <img className="img-thumbnail" src={xleThumbnailIcon} alt="" />
                                    <span className="img-info">
                                      <div className="img-name">{i.fileName}</div>
                                      <div className="img-size">
                                        <div>{i.fileType}</div>
                                        <div>{i.fileSize}</div>
                                      </div>
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      )}

                      {item.type === 2 && (
                        <div className="item itema">
                          <div className="con">
                            <div className="con-text fs-16">
                              <div className="voice-loader">
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}

                      {(item.type === 1 || item.type === 6 || item.questionType) && (
                        <div className="item itemb">
                          {index !== state.consultationList.length - 1 && (
                            <div className="ai-icon">
                              {item.questionType !== 8 && (
                                <>
                                  <img className="avatar" src={robotIcon} width="48px" height="48px" alt="" />
                                  <span>
                                    {state.checkedLang
                                      ? language.messageEN.appTitle
                                      : language.messageZH.appTitle}
                                  </span>
                                </>
                              )}
                            </div>
                          )}

                          {index !== state.consultationList.length - 1 && (
                            <div className="con">
                              <div
                                className="con-text fs-16"
                                dangerouslySetInnerHTML={{ __html: item.answerContent }}
                                onClick={handleClick}
                              ></div>

                              <div className="features">
                                {!item.isError && !state.isDisabled && item.requestId && (
                                  <div className="con-opt">
                                    <div className="left">
                                      <img
                                        src={refreshIcon}
                                        onClick={(e) => {
                                          e.stopPropagation();
                                          bindRefresh(item);
                                        }}
                                        alt=""
                                      />
                                      {!state.isReading && (
                                        <img
                                          src={readAloudIcon}
                                          onClick={() => readText(item.answerContent, item.isReading)}
                                          alt=""
                                        />
                                      )}
                                      {state.isReading && (
                                        <img
                                          src={cannotReadIcon}
                                          onClick={stopReading}
                                          alt=""
                                        />
                                      )}
                                    </div>
                                  </div>
                                )}

                                {item.isShowRate && (!item.isError && !state.isDisabled && item.requestId) && (
                                  <div className="rate">
                                    <div>
                                      {state.checkedLang
                                        ? language.messageEN.evaluation
                                        : language.messageZH.evaluation}
                                    </div>
                                    <div className="demo-rate-block">
                                      <Rate
                                        size="large"
                                        disabled={item.feedBackType == 99}
                                        value={item.feedBackScore}
                                        color={colors}
                                        onChange={(value) => onRateChange(value, item)}
                                      />
                                    </div>

                                    {!item.isShowRateOpBox && item.feedBackType !== 99 && (
                                      <div className="rate-submit">
                                        <div>
                                          {state.checkedLang
                                            ? language.messageEN.cancelAction
                                            : language.messageZH.cancelAction}
                                        </div>
                                        <div>
                                          {state.checkedLang
                                            ? language.messageEN.confirm
                                            : language.messageZH.confirm}
                                        </div>
                                      </div>
                                    )}

                                    {item.isShowRateOpBox && item.feedBackType !== 99 && (
                                      <div className="rate-submit active">
                                        <div
                                          onClick={(e) => {
                                            e.stopPropagation();
                                            let data = [...state.consultationList];
                                            data.forEach((i, cindex) => {
                                              if (i.requestId === item.requestId) {
                                                i.feedBackType = state.cancleLikeStatus;
                                                i.ratevalue = 0;
                                                i.isShowRateOpBox = false;
                                                i.feedBackScore = 0;
                                                if (cindex === data.length - 1) {
                                                  setState(prev => ({
                                                    ...prev,
                                                    isShowLikePopover: false,
                                                    consultationList: data
                                                  }));
                                                }
                                              }
                                            });
                                          }}
                                        >
                                          {state.checkedLang
                                            ? language.messageEN.cancelAction
                                            : language.messageZH.cancelAction}
                                        </div>
                                        <div
                                          onClick={(e) => {
                                            e.stopPropagation();
                                            showFeedBack(
                                              item.requestId,
                                              item.feedBackType == 2 ? 0 : 2,
                                              item.feedBackType,
                                              state.feedBackScore
                                            );
                                          }}
                                        >
                                          {state.checkedLang
                                            ? language.messageEN.confirm
                                            : language.messageZH.confirm}
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                )}
                              </div>

                              {state.printEnd &&
                                item.answerRaw &&
                                item.answerRaw.docReferencesDistinct &&
                                item.answerRaw.docReferencesDistinct.length > 0 && (
                                  <div className={`con-file ${item.requestId}`}>
                                    <Collapse activeKey={item.activeNames}>
                                      <Panel
                                        key="1"
                                        header={state.checkedLang
                                          ? language.messageEN.reference
                                          : language.messageZH.reference}
                                        className="activeName"
                                      >
                                        {item.answerRaw.docReferencesDistinct.map((citem, cindex) => (
                                          <div
                                            key={cindex}
                                            className={`file-item fs-14 ${citem.active ? 'active' : ''}`}
                                            onClick={() => openFile(citem)}
                                          >
                                            <span className="iconfont icon-lianjie fs-24"></span>
                                            {citem.docName || ""}
                                            {citem.indexId && citem.indexId.length > 0 && (
                                              citem.indexId.map(ditem => (
                                                <span key={ditem}>[{ditem}]</span>
                                              ))
                                            )}
                                          </div>
                                        ))}
                                      </Panel>
                                    </Collapse>
                                  </div>
                                )}

                              {state.printEnd &&
                                item.classification &&
                                item.classification.length > 0 && (
                                  <div className="con-file">
                                    <Collapse activeKey={item.activeNames1}>
                                      <Panel
                                        key="1"
                                        header={state.checkedLang
                                          ? language.messageEN.business
                                          : language.messageZH.business}
                                        className="activeName"
                                      >
                                        {item.classification.map((citem, cindex) => (
                                          <div
                                            key={cindex}
                                            className="file-item fs-4"
                                            dangerouslySetInnerHTML={{ __html: citem }}
                                          ></div>
                                        ))}
                                      </Panel>
                                    </Collapse>
                                  </div>
                                )}
                            </div>
                          )}
                        </div>
                      )}
                    </React.Fragment>
                  ))}

                  {state.guessList.length > 0 && state.printEnd && !state.isDisabled && (
                    <div className="guess-to-ask">
                      <span>
                        {state.checkedLang
                          ? language.messageEN.iswant
                          : language.messageZH.iswant}
                      </span>
                      <div className="ask-list">
                        {state.guessList.map((item, index) => (
                          <div
                            key={index}
                            className="list-text"
                            onClick={() => clickItemQa(item, 3)}
                          >
                            <div>{item}</div>
                            <img src={vectorIcon} alt="" />
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {!state.printEnd && (
                    <div className="item itemb print">
                      <div className="ai-icon" style={{marginLeft:"18px"}}>
                        {state.questionType !== 8 && (
                          <>
                            <img className="avatar" src={robotIcon} width="48px" height="48px" alt="" />
                            <span>
                              {state.checkedLang
                                ? language.messageEN.appTitle
                                : language.messageZH.appTitle}
                            </span>
                          </>
                        )}
                      </div>
                      <div className="con">
                        <div className="con-text">
                          {!state.printBackHtml && (
                            <div
                              className="think-style"
                              dangerouslySetInnerHTML={{ __html: state.printAllHtml }}
                            ></div>
                          )}

                        </div>
                        <div
                          className="con-text fs-16"
                          dangerouslySetInnerHTML={{ __html: state.printBackHtml }}
                        ></div>
                      </div>
                    </div>
                  )}

                  <div className="tuijian" v-if="!state.isDisabled">
                    {followUpContents.map((item, index) => (
                      <div
                        key={index}
                        onClick={() => seachQuestion(item)}
                      >
                        <span className="recommend-one">{item}</span>
                      </div>
                    ))}
                  </div>

                  {state.isWait && (
                    <div className="item itemb">
                      <div className="ai-icon">
                        {state.questionType !== 8 && (
                          <>
                            <img className="avatar" src={robotIcon} width="48px" height="48px" alt="" />
                            <span>
                              {state.checkedLang
                                ? language.messageEN.appTitle
                                : language.messageZH.appTitle}
                            </span>
                          </>
                        )}
                      </div>
                      <div className="con loading-mask">
                        {/* <div className="load-15">
                          <div className="k-loader k-circle"></div>
                        </div> */}
                        <div className="ball"></div>
                        <div className="ball"></div>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
          <div className="assistant-footer" onClick={(e) => e.stopPropagation()}>
            {state.imgList && state.imgList.length > 0 && !state.isDisabled && (
              <div className="img-preview">
                <div className="uploadImg">
                  {state.imgList.map((item, index) => (
                    <div className="img" key={index}>
                      <img className="img-thumbnail" src={item.imgUrl} alt="" />
                      <span className="img-info">
                        <div className="img-name">{item.imgName}</div>
                        <div className="img-size">
                          <div>{item.imgType}</div>
                          <div>{item.imgSize}</div>
                        </div>
                      </span>
                      <div className="closeImg">
                        <img
                          src={fileCloseIcon}
                          onClick={() => {
                            const newImgList = [...state.imgList];
                            newImgList.splice(index, 1);
                            setState(prev => ({ ...prev, imgList: newImgList }));
                          }}
                          alt=""
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div className="option-area">
              <div onClick={(e) => {
                e.stopPropagation();
                setState(prev => ({ ...prev, showArea: !prev.showArea }));
              }}>
              </div>

              <div className="input-box">
                <div className="textarea-wrapper">
                  {!state.isShowVoiceInput && (
                    <TextArea
                      id="textarea-box"
                      value={state.sendText}
                      placeholder={state.checkedLang
                        ? language.messageEN.placeholderArr[bot_index]
                        : language.messageZH.placeholderArr[bot_index]}
                      rows={state.inputFieldFocus ? 4 : 1}
                      autoSize={{ maxRows: 5 }}
                      disabled={state.isDisabled}
                      onBlur={getFooterHeight}
                      onFocus={() => setState(prev => ({ ...prev, inputFieldFocus: true }))}
                      onKeyDown={handleKeyDown}
                      className={!state.inputFieldFocus ? 'textareaellipsis' : ''}
                      resize="none"
                      onChange={(e) => setState(prev => ({ ...prev, sendText: e.target.value }))}
                      style={{
                        overflowY: 'auto',
                        maxHeight: '200px',
                        minHeight: '45px',
                        transition: 'all 0.3s ease',
                        width: '100%'
                      }}
                    />
                  )}
                </div>
              </div>
  

              <div style={{ display: 'flex', justifyContent: "space-between" }}  className='cursor-pointer'>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <img src={lineContainer} alt="Line Container" style={{ marginRight: '10px' }} />
                    <div style={{ position: 'relative', left: '-120px', color: 'gray' }}>
                      <img src={paper} alt="Symbols" style={{ marginRight: '5px' }} />
                      <span>添加内容</span>
                    </div>
                  </div>
                  <div className='send-container'>
                    {state.selectedAgent ? (
                      <Popover
                        content={agentContent}
                        title="选择智能体"
                        trigger="hover"
                        placement="top"
                      >
                        <span 
                          style={{ 
                            color: '#5CB2FF', 
                            marginRight: '10px',
                            cursor: state.isDisabled ? 'not-allowed' : 'pointer',
                            pointerEvents: state.isDisabled ? 'none' : 'auto',
                            opacity: state.isDisabled ? 0.5 : 1
                          }}
                        >
                          @{state.selectedAgent.title}
                        </span>
                      </Popover>
                    ) : (
                      <Popover
                        content={agentContent}
                        title="选择智能体" 
                        trigger="hover"
                        placement="top"
                      >
                        <img src={symbols} alt="Select Agent" style={{ cursor: state.isDisabled ? 'not-allowed' : 'pointer', pointerEvents: state.isDisabled ? 'none' : 'auto', opacity: state.isDisabled ? 0.5 : 1 }} />
                      </Popover>
                    )}
                    <img src={line} />
               {state.isDisabled}
                    {!state.fileLoading && (state.sendText || state.sendHidenText || state.imgList.length > 0|| state.isDisabled) ? (
                      <span>
                        {state.isDisabled && (
                          <img
                            src={stopIcon}
                            onClick={() => stopReceiveData(3)}
                            alt=""
                          />
                        )}
                        {!state.isDisabled && (
                          <img
                            src={state.sendText ? sendLight : send}
                            onClick={sendQa}
                            alt=""
                          />
                        )}
                      </span>
                    ) : (
                      <span>
                        {!state.isDisabled && (
                          <img src={send} alt="" />
                        )}
                      </span>
                    )}
                  </div>
                </div>

              <div>


                
           
              </div>

              {/* {isVisibleRecommendIcon && state.questionType !== 8 && (
                <div className="recommendIcon">
                  <span onClick={() => toggleVisibility(1)}>
                    {state.checkedLang
                      ? language.messageEN.discover
                      : language.messageZH.discover}
                  </span>
                </div>
              )} */}
            </div>

            {state.questionType === 8 && (
              <div className="assistant-footer-box">
                <div
                  className={`sen ${state.isSk ? 'sen-active' : ''}`}
                  onClick={() => {
                    setState(prev => ({ ...prev, isSk: !prev.isSk }));
                  }}
                >
                  <img
                    src={state.isSk ? skActiveIcon : skIcon}
                    style={{ width: '20px' }}
                    alt=""
                  />
                  深度思考
                </div>
              </div>
            )}
          </div>



          <Modal
            open={state.showFeedBack}
            title=""
            width="40%"
            style={{ padding: '12px' }}
            footer={null}
            onCancel={() => setState(prev => ({ ...prev, showFeedBack: false }))}
          >
            <div className="feedback-box">
              <div className="title">
                <div className="title-left">
                  {state.checkedLang
                    ? language.messageEN.feed
                    : language.messageZH.feed}
                </div>
              </div>
              <div className="feedback-content">
                <CheckboxGroup
                  value={state.feedBackChecked}
                  onChange={(values) => setState(prev => ({ ...prev, feedBackChecked: values }))}
                >
                  {state.feedBackSelect.map(i => (
                    <Checkbox key={i.dictCode} value={i.dictLabel}>
                      {i.dictLabel}
                    </Checkbox>
                  ))}
                </CheckboxGroup>
                <TextArea
                  value={state.feedBackText}
                  onChange={(e) => setState(prev => ({ ...prev, feedBackText: e.target.value }))}
                  className="feedback-textarea"
                  placeholder={state.checkedLang
                    ? language.messageEN.feedContent
                    : language.messageZH.feedContent}
                  rows={8}
                />
              </div>
            </div>
          </Modal>

    
        </div>
      )}

      {pageName === "文档库" && (
         <div style={{ width: '95%', height: '100vh', overflow: 'auto' }}>
          <SquareEnd />
        </div>
      )}

      {pageName === '问答' && isVisibleRecommendPopup && (
        <div className="assistant-popup" >
          <div className="recommend-box">
            <div className="recommend">
              <div className="list">
                <div className="desc">
                  <div className="robot">
                    <div className="dailyrecommendations">
                      {state.checkedLang
                        ? language.messageEN.bot_question[bot_index].desc
                        : language.messageZH.bot_question[bot_index].desc}
                    </div>

                  </div>
                  <div className="right">
                    <div className="close" onClick={() => toggleVisibility(1)}>
                      <img src={recommendCloseIcon} alt="关闭" />
                    </div>
                  </div>
                </div>

                {state.list.length > 0 ? (
                  state.list.map((item, index) => (
                    <div
                      key={index}
                      className="list-item"
                      onClick={() =>
                        isForbidden() ? '' :
                          clickItemQa(
                            state.checkedLang
                              ? item.quizContentEN
                              : item.quizContent,
                            4
                          )
                      }
                    >
                      <div className={`top-${index + 1}`}>{index + 1}</div>
                      <span className="item">
                        {state.checkedLang
                          ? item.quizContentEN
                          : item.quizContent}
                      </span>
                    </div>
                  ))
                ) : (
                  <div className="text" style={{ color: 'rgba(0, 0, 0, 0.8)' }}>
                    {state.checkedLang
                      ? language.messageEN.study
                      : language.messageZH.study}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

{pageName === "问答" &&
        <div className={`left-container ${!isVisibleAssistantLeft ? 'hidden' : ''}`}>
          <AssistantLeft
            ref={assistantLeftRef}
            isVisible={isVisibleAssistantLeft}
            onItemSelected={handleItemSelected}
            selectedItem={selectedHistoryItem}
            disableInitialSelection={disableInitialSelection} 
            onHistoryFirstItem={handleHistoryFirstItem}
            newHistoryItem={newHistoryItem}
            originPageType={originPageType} 
            disableClick={state.isDisabled}
          />
        </div>
      }
      <style jsx="true">{`
        .quest-list {
          line-height: 36px;
          font-size: 14px;
        }




        .home-card{
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
          padding: 20px;
          width:1000px;
          margin:20px auto;
        }
          .card-item{
          border-radius: 16px;
          background-color: white;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          padding: 10px 20px;
          height:117px;
         cursor: pointer;
          }
          .notice-icon{
          position: relative;
            top: 2px;
            margin-right: 10px;
          }
        .card-title-container{
            display: flex;
            align-items: center;
        }
        .card-title{
        font-weight:500;
        }


        .input-box {
          position: relative;
          flex: 1;
          display: flex;
          flex-direction: column;
        }
        .input-box textarea {
          overflow-y: auto;
          white-space: pre-wrap;
          word-wrap: break-word;
          border: none !important;
          min-height: 45px !important;
          padding: 10px;
          background: transparent;
        }
        #textarea-box {
          border: none !important;
          min-height: 45px !important;
          padding: 10px;
          background: transparent;
        }
        input:focus,
        textarea:focus,
        .assistant-container .assistant-footer .input-box textarea:focus,
        .assistant-container
          .assistant-footer
          .option-area
          .input-box
          textarea:focus,
        .el-textarea__inner:focus,
        #textarea-box:focus {
          outline: none !important;
          box-shadow: none !important;
          border-color: #e0e0e0 !important;
        }
        .assistant-right .cursor-point {
          cursor: pointer !important;
        }
        .assistant-container {
          width: 100%;
          display: flex;
          flex-direction: row;
          position: fixed;
          margin-left: 94px;
          background: #fff;
          z-index: 1;
          overflow: hidden;
          height: 100vh;
        }

        .assistant-right {
          width: 80%;
          height: 100vh;
          position: relative;
          overflow: hidden;
          display: flex;
          flex-direction: column;
        }

        .session-box {
          flex: 1;
          overflow-y: auto;
          padding-bottom: 20px;
        }

        .assistant-footer {
          width: 1000px;
          display: flex;
          flex-direction: column;
          margin: 0 auto;
          border-bottom: 2px solid #2ea3df;
          padding: 10px 30px;
          margin-top:-70px;
          background: #ffffff;
          box-shadow: 0px 4px 12px rgba(92, 178, 255, 0.2);
          z-index: 100;
          border-radius: 14px;
          position: relative;
          margin-top: auto;
        }

        .option-area {
          display: flex;
          flex-direction: column;
          width: 100%;
        }

        .input-box {
          position: relative;
          flex: 1;
          display: flex;
          flex-direction: column;
          width: 100%;
        }

        .textarea-wrapper {
          display: flex;
          flex-direction: column;
          width: 100%;
          position: relative;
        }

        .input-box textarea {
          overflow-y: auto;
          white-space: pre-wrap;
          word-wrap: break-word;
          border: none !important;
          min-height: 45px !important;
          padding: 10px;
          background: transparent;
          width: 100%;
          position: relative;
        }

        #textarea-box {
          border: none !important;
          min-height: 45px !important;
          padding: 10px;
          background: transparent;
          width: 100%;
          position: relative;
        }

        .assistant-right .cursor-point {
          cursor: pointer !important;
        }

        .assistant-container {
    width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: row;
  position: fixed;

  margin-left: 94px;
  background: #fff;
  z-index: 1;
      overflow: hidden;
  background: #fff;
          .assistant-left {
            width: 300px;
            height: 95vh;
          }

          /* 过渡效果 */
          .shrink-enter-active,
          .shrink-leave-active {
            transition: width 0.5s ease-in-out, opacity 0.5s ease-in-out;
            overflow: hidden;
            /* 防止内容溢出 */
          }

          /* 元素进入时的初始状态：宽度0，透明度0 */
          .shrink-enter {
            width: 0;
            opacity: 0;
          }

          /* 元素进入时的结束状态：宽度100%，透明度1 */
          .shrink-enter-to {
            width: 14vw;
            opacity: 1;
          }

          /* 元素离开时的初始状态：宽度100%，透明度1 */
          .shrink-leave {
            width: 14vw;
            opacity: 1;
          }

          /* 元素离开时的结束状态：宽度0，透明度0 */
          .shrink-leave-to {
            width: 0;
            opacity: 0;
          }

          .session-box {
            width: 56.5vw;
            height: 100%;
            margin: 0 auto;
            padding-right: 3px;
            overflow: auto;
          }

          .greet::-webkit-scrollbar {
            display: none;
          }
          .session-box::-webkit-scrollbar {
            display: none;
          }
          .assistant-right {
            width: 80%;
     
            height: 95vh;
            position: relative;
            overflow: hidden;
         

            .right-head {
              width: 100%;
              margin-top: 23px;
              gap: 20px;
              display: flex;
              align-items: center;
              font-size: 14px;

              justify-content: flex-end;
              .session-type {
                flex: 1;

                span {
                  font-size: 16px;
                }
              }

              .changeLange {
            display:flex;
          flex-direction: row;

                //margin-right: 1.6vw;
                > div {
                  display: flex;

                  > div {
                    width: 50%;
                  }

                  > div > span {
                    background: rgba(92, 178, 255, 0.15);
                    display: inline-block;
                    width: 100%;
                    height: 3.5vh;
                    text-align: center;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  }

             
                }

          
              }

              .changeLange:hover {
                cursor: pointer;
              }

              .version {
                width: 5.2vw;
                height: 3.5vh;
                border-radius: 3.5vh;
                background: rgba(92, 178, 255, 0.15);
                display: flex;
                align-items: center;
                justify-content: center;
              }

              .layout-1 {
                width: 9.9494vw;
              }

              .layout-2 {
                width: 7.0791vw;
              }

              div {
                display: inline-block;
              }
            }
          }

          .assistant-popup {
            border-radius: 14px;
            width: 300px;
            height: 100%;
            background: #fff;
            padding: 10px;
            padding-right: 20px;
            .recommend-box {
              font-size: 16px;
              width: 260px;
              height: calc(100% - 70px);
              margin: 0 auto;
              padding: 2.7vh;
              border-radius: 14px;
              background: #1196db0d;

              .desc {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .robot {
                  color: #999;
                  font-size: 12px;
                  margin-bottom: 1.1vh;

                  .dailyrecommendations {
                    color: #333;
                    font-size: 17px;
                  }

                  div:last-child {
                    line-height: 26px;
                  }
                }

                .right {
                  display: flex;
                  flex-direction: column;
                  margin-bottom: auto;
                }

                .close {
                  width: 16px;
                  height: 16px;
                  margin: 3px 0 4px;
                  margin-left: auto;

                  img {
                    width: 100%;
                    height: 100%;
                    font-size: 16px;
                  }
                }

                .close:hover {
                  cursor: pointer;
                }

                .refresh {
                  color: #5cb2ff;
                  font-size: 14px;
                  display: flex;
                  align-items: center;
                  gap: 5px;

                  span {
                    font-size: 16px;
                  }
                }

                .refresh:hover {
                  cursor: pointer;
                }
              }

              .nav-tab {
                width: 100%;
                height: 2.5vh;
                display: flex;
                margin-bottom: 1.2vh;

                .nav-item {
                  width: 25%;
                  height: 100%;
                  line-height: 2.5vh;
                  text-align: center;
                  color: #666;
                  display: inline-block;

                  .item-text {
                    line-height: 2.5vh;
                    text-align: center;
                    font-size: 12px;
                  }

                  &.active {
                    color: #5cb2ff;
                    border-bottom: #5cb2ff 1px solid;
                  }
                }
              }

              .nav-tab:hover {
                cursor: pointer;
              }

              .list-item {
                display: flex;
                align-items: center;

                div {
                  min-width: 2vh;
                  min-height: 2vh;
                  line-height: 2vh;
                  border-radius: 4px;
                  font-size: 15px;
                  display: inline-block;
                  text-align: center;
                  margin-right: 6px;
                  color: #999;
                }

                .top-1 {
                  background: #ea341c;
                  color: #fff;
                }

                .top-2 {
                  background: #f76f23;
                  color: #fff;
                }

                .top-3 {
                  background: #f7bb23;
                  color: #fff;
                }

                .item {
                  display: inline-block;
                  flex: 1;
                  text-align: left;
                  font-size: 14px;
                  margin: 1vh 0;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }

                .item:hover {
                  cursor: pointer;
                }
              }

              .text {
                font-size: 14px;
                font-weight: 400;
                line-height: 200px;
                text-align: center;
              }
            }
          }

          .ratesure {
            position: absolute;
            bottom: -36px;
            left: 0;
            right: 0;
            margin: auto;
            top: auto;
            width: 10%;
            display: flex;
            justify-content: center;

            img {
              width: 92px;
            }
          }

          .bg {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: row;
            border-radius: 14px;
            font-size: 14px;
            z-index: 101;
            background: #fff;
            box-shadow: 3px 0px 6px 0px rgba(92, 178, 255, 0.1);
          }

          .weather {
            height: 60px;
            display: flex;
            align-items: center;
            margin-left: 20px;
            font-weight: 600;
          }

          .tip {
            display: block;
            font-size: 28px;
            color: v-bind("themeColor.textColorLightest");
            margin: 20px 0;
            font-weight: 500;
          }

          .content {
            display: flex;
            margin-top: 24px;
            width: 100%;
            flex-direction: column;
            background: v-bind("themeColor.fillWhite");
            border-radius: 24px;

            &.consultation-mode {
              background: none;
              border-radius: 20px;
              overflow-y: scroll;
              margin: 0 auto;
              z-index: 100;
              width: calc(100% - 60px);

              &::-webkit-scrollbar {
                display: none;
              }
            }

            .desc {
              display: flex;
              color: v-bind("themeColor.textColor");
            }

            .guess-to-ask {
              & > span {
                color: #666;
                font-family: "PingFang SC";
                font-size: 14px;
                font-weight: 400;
                letter-spacing: 0px;
                margin-top: 14px;
                display: block;
              }

              .ask-list {
                margin-bottom: 10px;

                .list-text {
                  width: fit-content;
                  color: #333;
                  font-family: "PingFang SC";
                  font-size: 12px;
                  font-style: normal;
                  font-weight: 400;
                  border-radius: 14px;
                  border: 1px solid #e6edf4;
                  background: #fff;
                  margin-top: 10px;
                  padding: 10px 12px 10px 20px;
                  letter-spacing: 0px;
                  line-height: 34px;
                  display: flex;
                  flex-direction: row;
                  align-content: center;

                  img {
                    width: 8px;
                    height: 12px;
                    margin-left: 30px;
                  }
                }
              }
            }

            .consultation-container {
              margin: 2vh 0;
              display: flex;
              flex-direction: column;

              .greet {
                padding-top: 77px;
                overflow: scroll;

                .logo {
                  margin-right: 20px;

                  img {
                    margin-top: 5px;
                  }
                }

                .ai-icon {
                  width: 56.5vw;
                  display: flex;
                  margin: 0 auto;
                       justify-content: center;
                  font-size: 20px;
                  color: #333;
                  font-family: "PingFang SC";
                  font-style: normal;
                  font-weight: 400;
                  line-height: normal;

                  .con {
                    position: relative;

                    .userName {
                      color: #5cb2ff;
                    }

                    span {
                      font-weight: bold;
                    }

                    .con-text {
                      position: absolute;
                      color: #999;
                      font-size: 14px;
                      width: 1050px;
                      font-weight: 400;
                    }
                  }
                }

                .avatar {
                  width: 231px;
                  margin-top: -80px;
                }
              }

              .item.itemb {
                flex-direction: column;
                position: relative;

                .con {
                  width: auto;
                  border-radius: 14;
                  background-color: #fff;
                  box-shadow: 0px 0px 4px v-bind("themeColor.fillBlueLight");
                }

                .con.loading-mask {
                  width: auto;
                  border-radius: 14;
                  box-shadow: 0px 0px 0.021rem rgba(92, 178, 255, 0.4);
                }

                .load-15 {
                  font-size: 0.15rem;
                }

                .k-loader {
                  display: inline-block;
                  font-size: 0.15rem;
                  margin: 0 0.5em;
                  position: relative;
                  height: 10px;
                  width: 10px;
                }

                .k-loader:before,
                .k-loader:after {
                  content: "";
                  display: block;
                  height: 10px;
                  position: absolute;
                  width: 10px;
                }

                .k-loader:before {
                  animation: k-loadingK 1s ease-in-out infinite,
                    k-loadingM 0.33s ease-in-out infinite;
                  background-color: #5cb2ff;
                }

                .k-loader:after {
                  animation: k-loadingL 1s ease-in-out infinite,
                    k-loadingN 0.33s ease-in-out infinite;
                  background-color: #ffb1b1;
                }

                .k-small {
                  font-size: 1em;
                }

                .k-large {
                  font-size: 4em;
                }

                .k-circle:before,
                .k-circle:after {
                  border-radius: 50%;
                }

                .k-circle-before:before {
                  border-radius: 50%;
                }

                .k-circle-after:after {
                  border-radius: 50%;
                }

                @keyframes k-loadingK {
                  0% {
                    left: 0;
                    transform: scale(1.1);
                  }

                  50% {
                    left: 100%;
                    transform: scale(1);
                  }

                  100% {
                    left: 0;
                    transform: scale(1.1);
                  }
                }

                @keyframes k-loadingL {
                  0% {
                    left: 100%;
                    transform: scale(1.1);
                  }

                  50% {
                    left: 0;
                    transform: scale(1);
                  }

                  100% {
                    left: 100%;
                    transform: scale(1.1);
                  }
                }

                #loading {
                  height: 60px;
                  width: 100%;
                  z-index: 1;
                  margin-top: 0px;
                  top: 0px;
                }

                #loading-center {
                  position: relative;
                }

                #loading-center-absolute {
                  width: auto;
                }

                .object {
                  width: 8px;
                  height: 30px;
                  margin-right: 5px;
                  background: linear-gradient(
                    152.42deg,
                    #5cb2ff 17.78%,
                    #ffb1b1 100%
                  );
                  -webkit-animation: animate 1s infinite;
                  animation: animate 1s infinite;
                  float: left;
                }

                .object:last-child {
                  margin-right: 0px;
                }

                .object:nth-child(10) {
                  -webkit-animation-delay: 0.9s;
                  animation-delay: 0.9s;
                }

                .object:nth-child(9) {
                  -webkit-animation-delay: 0.8s;
                  animation-delay: 0.8s;
                }

                .object:nth-child(8) {
                  -webkit-animation-delay: 0.7s;
                  animation-delay: 0.7s;
                }

                .object:nth-child(7) {
                  -webkit-animation-delay: 0.6s;
                  animation-delay: 0.6s;
                }

                .object:nth-child(6) {
                  -webkit-animation-delay: 0.5s;
                  animation-delay: 0.5s;
                }

                .object:nth-child(5) {
                  -webkit-animation-delay: 0.4s;
                  animation-delay: 0.4s;
                }

                .object:nth-child(4) {
                  -webkit-animation-delay: 0.3s;
                  animation-delay: 0.3s;
                }

                .object:nth-child(3) {
                  -webkit-animation-delay: 0.2s;
                  animation-delay: 0.2s;
                }

                .object:nth-child(2) {
                  -webkit-animation-delay: 0.1s;
                  animation-delay: 0.1s;
                }

                @-webkit-keyframes animate {
                  50% {
                    -ms-transform: scaleY(0);
                    -webkit-transform: scaleY(0);
                    transform: scaleY(0);
                  }
                }

                @keyframes animate {
                  50% {
                    -ms-transform: scaleY(0);
                    -webkit-transform: scaleY(0);
                    transform: scaleY(0);
                  }
                }

                .ai-icon {
                  display: flex;
                  align-items: center;
                  margin-bottom: 10px;

                  img {
                    width: 29px;
                    height: auto;
                  }

                  span {
                    font-size: 16px;
                    font-weight: 500;
                    color: #999;
                    line-height: initial;
                    margin-left: 9px;
                    vertical-align: bottom;
                  }
                }

                .avatar {
                  margin: 0;
                }
              }

              .item.itema {
                display: flex;
                flex-direction: column;
                justify-content: flex-end;

                .file-qa {
                  .uploadImg {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 10px;
                    justify-content: flex-end;
                    margin-bottom: 14px;

                    .img {
                      width: 205px;
                      height: 50px;
                      padding: 10px;
                      border-radius: 10px;
                      position: relative;
                      border: 1px solid #e7e7e7;
                      background-color: #fff;
                      display: flex;
                      flex-direction: row;
                      gap: 8px;

                      .img-thumbnail {
                        width: 30px;
                        height: 30px;
                        border-radius: 5px;
                        object-fit: cover;
                      }

                      .img-info {
                        display: flex;
                        flex-direction: column;
                        justify-content: space-between;
                        height: 100%;

                        .img-name {
                          color: #000;
                          font-family: "PingFang SC";
                          font-size: 12px;
                          font-style: normal;
                          font-weight: 400;
                          max-width: 125px;
                          line-height: normal;
                          white-space: nowrap;
                          /* 禁止换行 */
                          overflow: hidden;
                          /* 隐藏溢出的文本 */
                          text-overflow: ellipsis;
                          /* 添加省略号 */
                        }

                        .img-size {
                          display: flex;
                          gap: 5px;
                          align-items: center;

                          div {
                            color: #999;
                            font-family: "PingFang SC";
                            font-size: 10px;
                            font-style: normal;
                            font-weight: 400;
                            line-height: normal;
                          }
                        }
                      }
                    }
                  }
                }

                .img-qa {
                  text-align: right;
                  width: 100%;
                  overflow: hidden;

                  img {
                    max-width: 60%;
                    /* 限制图片最大宽度为容器宽度 */
                    max-height: 400px;
                    /* 限制图片最大高度为400px */
                    height: auto;
                    /* 保持宽高比例 */
                    width: auto;
                    /* 保持宽高比例 */
                    object-fit: contain;
                    /* 保证图片自适应容器，且不会变形 */
                    border-radius: 14px;
                    padding: 14px 20px;
                    background-color: rgba(92, 178, 255, 0.3);
                  }
                }

                .con {
                  border-radius: 14px;
                  background: rgba(92, 178, 255, 0.3);
                  color: #333;
                  margin: 30px 0 20px auto;
                  width: fit-content;

                  .voice-loader {
                    margin: auto;
                    width: 155px;
                    height: 60px;
                    display: flex;
                    justify-content: center;
                    gap: 1px;
                  }

                  .voice-loader span {
                    display: block;
                    background: #fff;
                    width: 7px;
                    height: 10%;
                    border-radius: 14px;
                    margin-right: 5px;
                    float: left;
                    margin-top: 15%;
                  }

                  .voice-loader {
                    & > span:last-child {
                      margin-right: 0px;
                    }

                    & > span:nth-child(1) {
                      height: 20%;
                    }

                    & > span:nth-child(2) {
                      height: 40%;
                      margin-top: 10%;
                    }

                    & > span:nth-child(3) {
                      height: 60%;
                      margin-top: 5%;
                    }

                    & > span:nth-child(4) {
                      height: 80%;
                      margin-top: 0;
                    }

                    & > span:nth-child(5) {
                      height: 60%;
                      margin-top: 5%;
                    }

                    & > span:nth-child(6) {
                      height: 40%;
                      margin-top: 10%;
                    }

                    & > span:nth-child(7) {
                      height: 20%;
                      margin-top: 15%;
                    }
                  }

                  .voice-loader-animate {
                    & > span:last-child {
                      margin-right: 0px;
                    }

                    & > span:nth-child(1) {
                      animation: load 1.5s 1.4s infinite linear;
                    }

                    & > span:nth-child(2) {
                      animation: load 1.5s 1.2s infinite linear;
                    }

                    & > span:nth-child(3) {
                      animation: load 1.5s 1s infinite linear;
                    }

                    & > span:nth-child(4) {
                      animation: load 1.5s 0.8s infinite linear;
                    }

                    & > span:nth-child(5) {
                      animation: load 1.5s 0.6s infinite linear;
                    }

                    .loader span:nth-child(6) {
                      animation: load 2.5s 0.4s infinite linear;
                    }

                    .loader span:nth-child(7) {
                      animation: load 2.5s 0.2s infinite linear;
                    }
                  }

                  @keyframes load {
                    0% {
                      background: #fff;
                      margin-top: 15%;
                      height: 10%;
                    }

                    50% {
                      background: #f5f5f5;
                      height: 100%;
                      margin-top: 0%;
                    }

                    100% {
                      background: #fff;
                      height: 10%;
                      margin-top: 15%;
                    }
                  }
                }
              }

              .item {
                display: flex;
                justify-content: flex-end;
                margin-top: 20px;

                &:first-child {
                  margin-top: 0;
                }

                .module-type {
                  margin-top: 24px;

                  span {
                    margin-right: 24px;
                    font-size: 28px;
                    font-weight: 500;
                    letter-spacing: 0px;
                    line-height: 58px;
                    color: rgba(148, 162, 176, 1);
                    padding: 16px 50px;
                    border-radius: 220px;
                    background: rgba(240, 241, 242, 1);
                  }

                  span.active {
                    background: rgba(219, 238, 255, 1);
                    color: #5cb2ff;
                  }
                }

                .avatar {
                  margin-left: 16px;
                  width: 51.6px;
                  margin-right: 16px;
                }

                &:nth-child(2n) {
                  justify-content: flex-end;

                  .avatar {
                    margin-left: 16px;
                  }
                }

                .con {
                  max-width: 100%;
                  display: flex;
                  flex-direction: column;
                  padding: 14px 20px;
                  border-radius: 24px;
                  color: v-bind("themeColor.textColor");
                  // box-shadow: 0px 0px 8px v-bind("themeColor.shadowColor");
                  // font-size: 28px;
                  overflow: hidden;

                  .con-text {
                    display: flex;
                    flex-direction: column;
                    // white-space: pre-wrap;
                    overflow: hidden;

                    ref {
                      color: #999;
                    }

                    li {
                      a {
                        color: #5cb2ff;
                      }
                    }

                    a {
                      color: #5cb2ff !important;
                    }

                    .docname {
                      font-size: 24px;
                      color: v-bind("themeColor.textColor");
                    }

                    span {
                      font-size: 28px;
                    }

                    .think-style {
                      // color: #999;
                    }
                  }

                  .con-file {
                    display: flex;
                    flex-direction: column;
                    margin-top: 20px;
                    gap: 6px;

                    .el-collapse-item__header {
                      font-size: 10px !important;
                      height: 35px !important;
                    }

                    .activeName {
                      color: #333;
                      font-family: "PingFang SC";
                      font-size: 14px;
                      font-style: normal;
                      font-weight: 400;
                      line-height: normal;
                    }

                    .fromto {
                      color: v-bind("themeColor.textColorLighten");
                    }

                    .file-item {
                      color: #666;
                      font-family: "PingFang SC";
                      font-size: 14px;
                      font-style: normal;
                      font-weight: 400;
                      line-height: normal;
                      margin: 4px 0px;
                      word-break: break-all;

                      &.active {
                        color: #5cb2ff;
                      }

                      div:last-child {
                        margin-top: 20px;
                      }

                      a {
                        text-decoration: underline;
                        color: #5cb2ff;
                      }

                      .iconfont {
                        color: #5cb2ff;
                        margin-right: 4px;
                      }
                    }
                  }

                  // .features {
                  //   display: flex;
                  //   flex-direction: row;
                  //   justify-content: space-between;
                  //   align-content: center;
                  //   font-size: 14px;
                  //   height: 40px;
                  // }

                  .con-opt {
                    display: flex;
                    justify-content: space-between;

                    .left {
                      display: flex;
                      align-items: center;

                      img {
                        width: 14px;
                        margin-right: 26px;
                      }

                      img:hover {
                        cursor: pointer;
                      }

                      span {
                        margin-left: 68px;

                        &:first-child {
                          margin-left: 0;
                        }

                        &.icon-good-a-copy,
                        &.icon-quxiaodianzan-a-copy {
                          color: #e97600;
                        }
                      }
                    }

                    .right {
                      img {
                        width: 36px;
                        margin-left: 45px;
                      }
                    }
                  }
                }
              }
            }
          }

          .rate {
            display: flex;
            flex-direction: row;
            flex-wrap: nowrap;
            align-items: center;

            .demo-rate-block {
              margin-left: 15px;
            }

            .rate-submit {
              margin-left: 8px;

              div {
                display: inline-block;
                margin-right: 10px;
                color: #999;
                font-family: "PingFang SC";
                font-size: 14px;
                font-style: normal;
                font-weight: 400;
              }

              &.active {
                div {
                  color: #5cb2ff;
                }

                div:hover {
                  cursor: pointer;
                }
              }
            }

            & > div {
              color: #666;
              font-family: "PingFang SC";
              font-size: 14px;
              font-style: normal;
              font-weight: 400;
            }
          }

          .cxb-box {
            // position: fixed;
            z-index: 15;

            .cxb {
              img {
                width: 100px;
              }
            }

            .cxb-text {
              position: absolute;
              top: 0;
              left: 80px;

              img {
                width: 136px;
                margin-top: 20px;
              }
            }
          }

          .img-preview {
            background: #ffffff;
            width: 100%;
            padding: 20px 0 30px;

            .uploadImg {
              width: 100%;
              overflow-x: auto;
              display: flex;
              gap: 10px;

              .img {
                width: 205px;
                height: 50px;
                padding: 10px;
                border-radius: 10px;
                flex-shrink: 0;
                /* 防止子元素收缩 */
                position: relative;
                border: 1px solid #e7e7e7;
                display: flex;
                flex-direction: row;
                gap: 8px;

                .img-thumbnail {
                  width: 30px;
                  height: 30px;
                  border-radius: 5px;
                  object-fit: cover;
                }

                .img-info {
                  display: flex;
                  flex-direction: column;
                  justify-content: space-between;
                  height: 100%;

                  .img-name {
                    color: #000;
                    font-family: "PingFang SC";
                    font-size: 11px;
                    font-style: normal;
                    font-weight: 400;
                    max-width: 125px;
                    line-height: normal;
                    white-space: nowrap;
                    /* 禁止换行 */
                    overflow: hidden;
                    /* 隐藏溢出的文本 */
                    text-overflow: ellipsis;
                    /* 添加省略号 */
                  }

                  .img-size {
                    display: flex;
                    gap: 5px;
                    align-items: center;

                    div {
                      color: #999;
                      font-family: "PingFang SC";
                      font-size: 10px;
                      font-style: normal;
                      font-weight: 400;
                      line-height: normal;
                    }
                  }
                }

                .closeImg {
                  font-size: 0px;
                  top: 6px;
                  right: 8px;
                  position: absolute;

                  img {
                    width: 14px;
                    height: 14px;
                    object-fit: contain;
                  }

                  img:hover {
                    cursor: pointer;
                  }
                }
              }
            }
          }

          .assistant-footer {
            width: 1000px;
            display: flex;
            flex-direction: column;
         margin: 0 auto;
          border-bottom: 2px solid #2ea3df;
            padding: 10px 30px;
            background: #ffffff;
            box-shadow: 0px 4px 12px rgba(92, 178, 255, 0.2);
            z-index: 100;
            border-radius: 14px;
            position: relative;
            // 上传图片缩略图

            .fileUpload {
              position: absolute;
              width: 346px;
              height: 90px;
              display: flex;
              top: -90px;
              left: 0;
              z-index: 200;

              .select {
                width: 116px;
                height: 82px;
                border-radius: 10px;
                background: #fff;
                box-shadow: 0px 4px 12px 0px rgba(92, 178, 255, 0.2);
                padding: 17px;
                color: #333;
                font-size: 14px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                margin-top: 8px;

                div {
                  display: flex;
                  align-items: center;

                  img {
                    width: 16px;
                    height: 16px;
                    margin-right: 7px;
                  }
                }

                div:hover {
                  cursor: pointer;
                }
              }

              .tips {
                width: 226px;
                height: 69px;
                margin-bottom: 20px;
                position: relative;

                img {
                  width: 226px;
                  height: 69px;
                }

                p {
                  position: absolute;
                  top: 10px;
                  right: 10px;
                  color: #fff;
                  font-family: "PingFang SC";
                  font-size: 12px;
                  width: 198px;
                  height: 49px;
                }
              }
            }

            .recommendIcon {
              position: absolute;
              width: 86px;
              height: 28px;
              top: -100px;
              right: 0;

              div {
                position: relative;
              }

              img {
                position: absolute;
                top: -32px;
                left: 11px;
                width: 29px;
                height: 35px;
              }

              span {
                display: block;
                width: 100%;
                height: 28px;
                border-radius: 15px;
                background: #5cb2ff;
                color: #fff;
                font-size: 14px;
                line-height: 28px;
                text-align: center;
              }

              span:hover {
                cursor: pointer;
              }
            }

            .option-area {
              display: flex;
              flex-direction: column;
              width: 100%;
            }

            .area-con {
              display: flex;
              width: 100%;
              padding: 20px 0;
              border-top: 1px solid #f5f5f5;

              .van-row {
                width: 100%;
                justify-content: center;
              }

              .area-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                color: v-bind("themeColor.textColorLighten");
                font-size: 24px;

                img {
                  width: 86px;
                  margin-bottom: 10px;
                  border: 1px dashed v-bind("themeColor.borderColorLighten");
                }
              }
            }

            .ver {
              position: absolute;
              bottom: 103%;
              left: 0;
              right: 0;
              margin: auto;
              text-align: center;
              font-size: 20px;
              color: #4c4c4c;
              opacity: 0.5;
            }
          }

          .warn {
            bottom: 16px;
            left: 50%;
            transform: translateX(-50%);
            position: absolute;
            text-align: center;
            margin-top: 36px;
            color: #999;
            font-family: "PingFang SC";
            font-size: 12px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
          }
        }

        .feedback-box {
          .title {
            font-size: 16px;
          }

          .sub {
            width: 94%;
            display: flex;
            flex-direction: row-reverse;
            margin: 10px 30px 0;
          }
        }

        .loading-mask {
          width: 40px;
          height: 40px;
          position: relative;
        }

        /* 小球样式 */
        .ball {
          width: 10px;
          height: 10px;
          border-radius: 50%;
          position: absolute;
          top: 50%;
          left: 30px;
          transform-origin: 10px; /* 设置小球旋转半径 */
          animation: rotate 1s linear infinite; /* 小球旋转动画 */
        }

        .ball:nth-child(1) {
          background-color: #5cb2ff; /* 蓝色 */
          animation-delay: 0s;
        }

        .ball:nth-child(2) {
          background-color: #ffb1b1; /* 粉红色 */
          animation-delay: -0.5s;
        }

        /* 定义关键帧 */
        @keyframes rotate {
          0% {
            transform: translateX(-10px) translateY(-50%); /* 左边起点 */
          }
          50% {
            transform: translateX(10px) translateY(-50%); /* 右边终点 */
          }
          100% {
            transform: translateX(-10px) translateY(-50%); /* 回到左边起点 */
          }
        }

        .versions {
          background-color: rgba(92, 178, 255, 0.15);
          width: 100px;
          height: 30px;
          display: flex;
          margin-right: 20px;
          line-height: 1.7vw;
          align-items: center !important;
          justify-content: center !important;
          text-align: center;
          border-radius: 4vh;
        }

        .left-container {
          width: 500px; /* Full width when visible */
          height: 95vh;
          transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1),
            width 0.5s cubic-bezier(0.4, 0, 0.2, 1); /* Smoother, more gradual transition */
          overflow: hidden;
          will-change: transform, width; /* Performance optimization for animations */
        }

        .left-container.hidden {
          transform: translateX(-100%);
          width: 0;
        }

        .recommend-box {
          font-size: 16px;
          width: 56.5vw;
          margin: 4.8vh auto 0;
          padding: 2.7vh;
          border-radius: 14px;
          background: #1196db0d;

          .desc {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .robot {
              color: #999;
              font-size: 12px;
              margin-bottom: 1.1vh;

              .dailyrecommendations {
                color: rgba(129, 170, 171);
                font-size: 20px;
              }

              div:last-child {
                line-height: 26px;
              }
            }

            .refresh {
              color: #5cb2ff;
              font-size: 14px;
              display: flex;
              align-items: center;
              gap: 5px;

              span {
                font-size: 16px;
              }
            }

            .refresh:hover {
              cursor: pointer;
            }
          }

          .nav-tab {
            width: 100%;
            height: 2.5vh;
            display: flex;
            margin-bottom: 1.2vh;

            .nav-item {
              width: 25%;
              height: 100%;
              line-height: 2.5vh;
              text-align: center;
              color: #666;
              display: inline-block;

              .item-text {
                line-height: 2.5vh;
                text-align: center;
                font-size: 12px;
              }

              &.active {
                color: #5cb2ff;
                border-bottom: #5cb2ff 1px solid;
              }
            }
          }

          .nav-tab:hover {
            cursor: pointer;
          }

          .list-item {
            display: flex;
            align-items: center;

            div {
              min-width: 2vh;
              min-height: 2vh;
              line-height: 2vh;
              border-radius: 4px;
              font-size: 15px;
              display: inline-block;
              text-align: center;
              margin-right: 6px;
              color: #999;
            }

            .top-1 {
              background: #ea341c;
              color: #fff;
            }

            .top-2 {
              background: #f76f23;
              color: #fff;
            }

            .top-3 {
              background: #f7bb23;
              color: #fff;
            }

            .item {
              display: inline-block;
              flex: 1;
              text-align: left;
              font-size: 14px;
              margin: 1vh 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .item:hover {
              cursor: pointer;
            }
          }

          .text {
            font-size: 14px;
            font-weight: 400;
            line-height: 200px;
            text-align: center;
          }
        }

        .changeLange {
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  padding: 5px;
  border-radius: 4px;
}

.language-option {
  cursor: pointer;
  margin: 0 5px;
}

.separator {
  margin: 0 5px;
}

.active-lang {
  color: #259edd; /* 选中的文字变蓝 */
}

  .new-chart{
  display: flex !important;
 gap:6px;
    font-weight: 500;
    border: 1px solid #ccc;
    padding: 5px 10px;
    border-radius: 4px;
      cursor:pointer;
  
  }
    .cursor-pointer{
    cursor:pointer;
    }

        .left-container {
          width: 500px;
          height: 85vh;
          position: absolute;
          right: 0;  /* Changed from left: 0 to right: 0 */
          top: 0;
        margin:20px 0;
             border-left:2px solid #f5f5f5;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          transform: translateX(0);
          opacity: 1;
          visibility: visible;
          z-index: 100;
        }

        .left-container.hidden {
          transform: translateX(100%); /* Changed from -100% to 100% */
          opacity: 0;
          visibility: hidden;
        }

          .cursor-pointer {
          cursor: pointer;
          transition: transform 0.3s ease;
        }

        .cursor-pointer.active {
          transform: rotate(180deg);
        }

        .assistant-right {
          position: relative;
          transition: margin-right 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* Changed from margin-left */
          margin-right: ${isVisibleAssistantLeft ? '300px' : '0'}; /* Changed from margin-left */
          width: auto;
        }
          .send-container{
          display:flex;
        gap:10px;
            align-items: center;
         cursor: pointer;
          }
        .send-container img{
          
          widht:25px;height:25px}
          .mainHeader-109{
          display: none !important;
          }
                  .u_c_4ade22aa{
            display: flex !important;
    flex-direction: row !important;
            }
    .notAllow{
    cursor: not-allowed;
    }
    .headerRow-50.headerRow-50.headerRow-50.headerRow-50.headerRow-50{
              display: none !important;
    }
              
                  .c_b_4ade22aa{
            display: flex !important;
    flex-direction: row !important;
            }
              /* 使用深度选择器 */
          :global(.c_b_4ade22aa) {
            display: flex !important;
            flex-direction: row !important;
            width: 100% !important;
          }

          /* 使用属性选择器进行样式穿透 */
          :global([class*="c_b_4ade22aa"]) {
            display: flex !important;
            flex-direction: row !important;
            width: 100% !important;
          }
:deep(.c_b_4ade22aa){
     display: flex !important;
            flex-direction: row !important;
            width: 100% !important;
}
      `}</style>
    </div>
  );
};

export default AssistantContainer;
